package com.alibaba.japan.club.runtime.springmvc.servlet.handler;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import org.springframework.beans.BeansException;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;

import com.alibaba.japan.club.runtime.springmvc.module.ModulePattern;

/**
 * 此类扩展了Spring MVC的SimpleUrlHandlerMapping<br>
 * 加入了自定义url mapping的规则
 * 
 * @author:shaochuan.wangsc
 * @date:2009-3-24
 * 
 */
public class JapanSimpleUrlHandlerMapping extends SimpleUrlHandlerMapping {

	private ModulePattern modulePattern;

	private Map<String, String> moduleUrlMap = new LinkedHashMap<String, String>();

	public void setModuleUrlMap(Map<String, String> moduleUrlMap) {
		this.moduleUrlMap = moduleUrlMap;
	}

	public void setModulePattern(ModulePattern modulePattern) {
		this.modulePattern = modulePattern;
	}

	@SuppressWarnings("unchecked")
	private void initModuleUrlMap() {
		Map<String, Object> urlMap = getUrlMap();
		Map<String, Object> urlMapping = modulePattern.getUrlMapping();
		for (Entry<String, String> entry : moduleUrlMap.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if (urlMap.get(key) == null) {
				urlMap.put(key, urlMapping.get(value));
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void initCustomerUrlMapping() {
		Map<String, Object> urlMap = getUrlMap();
		Map<String, Object> urlMapping = modulePattern.getUrlMapping();
		for (Entry<String, Object> entry : urlMapping.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (urlMap.get(key) == null) {
				urlMap.put(key, value);
			}
		}
	}

	/**
	 * Map URL paths to handler bean names. This is the typical way of configuring this HandlerMapping.
	 * <p>
	 * Supports direct URL matches and Ant-style pattern matches. For syntax details, see the
	 * {@link org.springframework.util.AntPathMatcher} javadoc.
	 * 
	 * @param mappings properties with URLs as keys and bean names as values
	 * @see #setUrlMap
	 */
	public void setMappings(Properties mappings) {
		setUrlMap(mappings);
	}

	/**
	 * Set a Map with URL paths as keys and handler beans (or handler bean names) as values. Convenient for population
	 * with bean references.
	 * <p>
	 * Supports direct URL matches and Ant-style pattern matches. For syntax details, see the
	 * {@link org.springframework.util.AntPathMatcher} javadoc.
	 * 
	 * @param urlMap map with URLs as keys and beans as values
	 * @see #setMappings
	 */
	@SuppressWarnings("unchecked")
	public void setUrlMap(Map urlMap) {
		if (urlMap != null) {
			getUrlMap().putAll(urlMap);
		}
	}

	@Override
	public void initApplicationContext() throws BeansException {
		initModuleUrlMap();
		initCustomerUrlMapping();
		super.initApplicationContext();
	}

}
